package baseclass.c_globalToPartMatrix;

/**
 * @date 2020/2/27 22:50
 */
public class Code03_ZigZagPrintMatrix {

    public static void main(String[] args) {
        int[][] matrix = {{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}};
        for (int i = 0; i < matrix.length; i++) {
            for (int j = 0; j < matrix[0].length; j++) {
                System.out.print(matrix[i][j]+" ");
            }
            System.out.println();
        }
        printZigZag(matrix);
    }

    public static void printZigZag(int[][] m) {
        int row = m.length - 1;
        int col = m[0].length - 1;
        //从A点和B点开始，A往下走，B往右走。
        int Arow = 0;
        int Acol = 0;
        int Brow = 0;
        int Bcol = 0;
        boolean up = true;
        while (Acol <= col) {
            print(m, up, Arow, Acol, Brow, Bcol);
            up = !up;
            //如果A点走到了最后一行，则A往右走
            if (Arow == row) {
                Acol++;
            } else { //否则就是A往下，B往右
                Arow++;
            }
            //如果B点走到了最后一列，则B往下走
            if (Bcol == col) {
                Brow++;
            } else { //否则就是A往下，B往右
                Bcol++;
            }
        }
    }

    public static void print(int[][] m, boolean up, int aRow, int aCol, int bRow
            , int bCol) {
        if (up) {
           while (aCol <= bCol){
               System.out.print(m[aRow--][aCol++]+" ");
           }
        }
        //down
        while (bCol >= aCol){
            System.out.print(m[bRow++][bCol--]+" ");
        }

    }
}
